package serial.usb

import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbManager
import kotlinx.coroutines.CompletableDeferred

private const val ACTION_USB_PERMISSION = "USB.PERMISSION"

suspend fun openUsb(context: Context, usb: UsbManager, device: UsbDevice): UsbDeviceConnection {
    val ret = usb.hasPermission(device)
    if (!ret) {
        requestPermission(context, usb, device)
    }
    return usb.openDevice(device)
}

private suspend fun requestPermission(context: Context, usb: UsbManager, device: UsbDevice) {
    val usbReceiver = UsbPermissionReceiver()
    val filter = IntentFilter(ACTION_USB_PERMISSION)

    context.registerReceiver(usbReceiver, filter)

    val intent = Intent(ACTION_USB_PERMISSION)
    intent.setPackage(context.packageName)
    val pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_MUTABLE)

    usb.requestPermission(device, pi)
    val ret = usbReceiver.promise.await()
    context.unregisterReceiver(usbReceiver)
    if (!ret) {
        throw IllegalStateException("没有获取usb权限")
    }
}

private class UsbPermissionReceiver() : BroadcastReceiver() {

    val promise = CompletableDeferred<Boolean>()

    override fun onReceive(context: Context?, intent: Intent?) {
        if (intent == null) {
            return
        }
        val flag = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
        promise.complete(flag)
    }
}
